/**
 * 
 */
package controller;

import com.example.remotecontrol.R;
import common.Constant;
import components.KeyboardManager;
import components.PasscodeManager;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author User
 * 
 */
public class PasscodeActivity extends Activity implements OnClickListener, OnKeyListener {

	public final static int RESULT_STOP = 2;
	public final static int RESULT_FINISH = 3;

	private EditText _editPasscode;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setTitle("Nhập mã bảo vệ");
		setContentView(R.layout.passcode_activity);

		findViewById(R.id.passcode_btn_ok).setOnClickListener(this);
		_editPasscode = (EditText)  findViewById(R.id.passcode_edit_passcode);
		KeyboardManager.showKeyboard( _editPasscode, this);
		_editPasscode.setOnKeyListener(this);
	}

	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.passcode_btn_ok:
			PasscodeManager passcodeManager = PasscodeManager.sharedPasscode(this);

			String inputPasscode = ((TextView) findViewById(R.id.passcode_edit_passcode))
					.getText().toString();

			if (passcodeManager.login(inputPasscode)) {
				if (getParent() == null) {
				setResult(RESULT_OK, getIntent());
				} else {
					getParent().setResult(RESULT_OK, getIntent());
				}
				
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				finish();
				
			} else {
				Toast.makeText(this, R.string.passcode_is_not_match,
						Toast.LENGTH_SHORT).show();
			}
			break;

		default:
			break;
		}
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

		// setResult(RESULT_STOP);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		//setResult(RESULT_FINISH);
		// finish();
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& keyCode == KeyEvent.KEYCODE_ENTER) {
			onClick(findViewById(R.id.passcode_btn_ok));
		} 
			
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return true;
		}
		return false;
	}
	
	 

}
